package com.pets.springboot_petshop.controller;


import com.pets.springboot_petshop.entity.Admin;
import com.pets.springboot_petshop.entity.AdminDTO;
import com.pets.springboot_petshop.pojo.Result;
import com.pets.springboot_petshop.service.AdminService;
import com.pets.springboot_petshop.service.EmailService;
import com.pets.springboot_petshop.util.JwtUtil;
import com.pets.springboot_petshop.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: wxk
 * @Email: 2089967794@qq.com
 * @Date: 2024/10/8 上午9:44 周二
 * @Description: 管理员控制层
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private CacheManager cacheManager;

    @PostMapping("/login")
    public Result<String> login(
            @NotBlank(message = "邮箱不能为空")
            @Pattern(regexp = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$", message = "邮箱格式不正确")
            @RequestParam("email") String email,
            @NotBlank(message = "密码不能为空")
            @Pattern(regexp = "^.{5,16}$", message = "密码长度必须在5到16个字符之间")
            @RequestParam("password") String password) {
        //根据邮箱查询
        Admin admin = adminService.findByAdminemail(email);
        //判断用户是否存在
        if (admin == null) {
            return Result.error("邮箱错误");
        }

        //判断密码是否正确
        //先进行加密再进行对比
        if (Md5Util.getMD5String(password).equals(admin.getPassword())) {
            //登录成功
            Map<String, Object> map = new HashMap<>();
            map.put("id", admin.getId());
            map.put("username", admin.getUsername());
            String token = JwtUtil.genToken(map);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/findByAdminName")
    public Result findByAdminName(@RequestParam String username) {
        Admin admin = adminService.findByAdminName(username);
        if (admin == null) {
            return Result.error("不存在用户");
        } else {
            AdminDTO adminDTO = adminService.convertToDTO(admin);
            return Result.success(adminDTO);
        }
    }

    @GetMapping("/findByAdminemail")
    public Result findByAdminemail(@RequestParam String email) {
        Admin admin = adminService.findByAdminemail(email);
        if (admin == null) {
            return Result.error("不存在用户");
        } else {
            AdminDTO adminDTO = adminService.convertToDTO(admin);
            return Result.success(adminDTO);
        }
    }
    // 根据用户名模糊查询用户
    @GetMapping("/selectusername")
    public Result<List<Admin>> selectusername(@RequestParam String username){
        List<Admin> admins = adminService.selectusername(username);
        if (admins.isEmpty()) {
            return Result.error("没有找到匹配的用户");
        } else {
            return Result.success(admins);
        }
    }

    // 根据用户邮箱模糊查询用户
    @GetMapping("/selectemail")
    public Result<List<Admin>> selectemail(@RequestParam String email){
        List<Admin> admins = adminService.selectemail(email);
        if (admins.isEmpty()) {
            return Result.error("没有找到匹配的用户");
        } else {
            return Result.success(admins);
        }
    }

    // 发送验证码
    @GetMapping("/sendCode")
    public Result<String> sendCode(@RequestParam String email) {
        if (email == null || email.trim().isEmpty()) {
            return Result.error("邮箱不能为空");
        }
        System.out.println("发送验证码请求：邮箱 = " + email);

        String randomCode = emailService.sendemail(email);
        cacheCode(email, randomCode);
        System.out.println("验证码已发送至邮箱：" + email);

        return Result.success("验证码已发送至您的邮箱");
    }

    // 检查验证码
    @GetMapping("/checkCode")
    public Result<String> checkCode(@RequestParam String code, @RequestParam String email) {
        System.out.println("检查验证码请求：邮箱 = " + email + ", 输入的验证码 = " + code);
        String cachedCode = getCodeFromCache(email);
        if (cachedCode == null || !cachedCode.equals(code)) {
            return Result.error("验证码错误或已过期");
        }
        removeFromCache(email);
        System.out.println("验证码正确");

        return Result.success("验证码正确");
    }

    // 修改密码
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody Admin admin) {
        System.out.println("修改密码请求: " + admin);
        String cachedCode = getCodeFromCache(admin.getEmail());
        if (cachedCode == null || !cachedCode.equals(admin.getVerificationCode())) {
            return Result.error("验证码错误或已过期");
        }
        removeFromCache(admin.getEmail());
        boolean updateSuccess = adminService.updateAdminpassword(admin);
        if (updateSuccess) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }
    }

    @PostMapping("/register")
    public Result registerUser(@RequestBody Map<String, String> payload) {
        String username = payload.get("username");
        String password = payload.get("password");
        String role = payload.get("role");
        String email = payload.get("email");
        String code = payload.get("code"); // 验证码

        // 验证邮箱验证码
        Result<String> checkCodeResult = checkCode(code, email);
        if (!checkCodeResult.isSuccess()) {
            return Result.error("验证码错误");
        }

        Admin existingAdminByEmail = adminService.findByAdminemail(email);
        Admin existingAdminByUsername = adminService.findByAdminName(username);
        if (existingAdminByEmail != null) {
            return Result.error("邮箱已使用");
        }
        if (existingAdminByUsername != null) {
            return Result.error("用户名已被占用");
        }

        // 注册新用户
        adminService.addAdmin(username, password,role, email);
        return Result.success("注册成功");
    }

    @Cacheable(value = "verificationCodes", key = "#email")
    public String getCodeFromCache(String email) {
        return cacheManager.getCache("verificationCodes").get(email, String.class);
    }

    public void cacheCode(String email, String code) {
        cacheManager.getCache("verificationCodes").put(email, code);
    }

    @CacheEvict(value = "verificationCodes", key = "#email")
    public void removeFromCache(String email) {
    }

    @GetMapping("/adminInfo")
    public Result<AdminDTO> adminInfo(@RequestHeader(name = "Authorization") String token) {
        // 根据令牌查询相应的用户信息
        Map<String,Object> map = JwtUtil.parseToken(token);
        int id = (int) map.get("id");

        Admin admin = adminService.select(id);
        if (admin == null) {
            return Result.error("不存在用户");
        } else {
            // 将Admin对象转换为AdminDTO对象
            AdminDTO adminDTO = adminService.convertToDTO(admin);
            return Result.success(adminDTO);
        }
    }
    @GetMapping("/adminfindAll")
    public Result<List<AdminDTO>> adminfindAll() {
        // 获取所有Admin对象的列表
        List<Admin> admins = adminService.findAll();
        if (admins == null || admins.isEmpty()) {
            return Result.error("获取数据失败");
        } else {
            // 将Admin对象列表转换为AdminDTO对象列表
            List<AdminDTO> adminDTOs = admins.stream()
                    .map(admin -> adminService.convertToDTO(admin))
                    .collect(Collectors.toList());
            return Result.success(adminDTOs);
        }
    }

     @PostMapping("/updateAdminById")
    public Result<Admin> updateAdminById(@RequestBody Admin admin){
        if (adminService.updateAdminById(admin)>0) {
            return Result.success(admin);
        }else {
            return Result.error("修改数据失败");
        }
     }
     @PostMapping("/deleteAdminById")
    public Result deleteAdminById(@RequestParam int id){
         System.out.println(id);
         if (adminService.deleteAdminById(id)>0){
             return Result.success("删除成功");
         }else {
             return Result.error("删除失败");
         }
     }
     
}
